package com.study.talk.ui.app.register.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.study.talk.R
import com.study.talk.ui.app.base.EventBusBaseFragment
import com.study.talk.databinding.FragmentPhoneNumberBinding
import com.study.talk.netty.message.response.SmsSendResponse
import com.study.talk.ui.app.register.RegisterViewModel
import com.study.talk.utils.extras.showToast
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@AndroidEntryPoint
class PhoneNumberFragment : EventBusBaseFragment() {

    private lateinit var binding: FragmentPhoneNumberBinding

    private val parentViewModel by lazy { ViewModelProvider(requireActivity())[RegisterViewModel::class] }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_phone_number,container, false)
        binding.vm = parentViewModel
        binding.lifecycleOwner = this
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.toCodeBtn.setOnClickListener {
            if (parentViewModel.phoneCheck()){
                parentViewModel.phoneSubmit()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSmsMessage(message: SmsSendResponse) {
        if (message.status == "OK") {
            parentViewModel.receiverMsg(message)
            findNavController().navigate(R.id.action_phoneNumberFragment_to_codeFragment)
        } else {
            showToast(message.message)
        }
    }
}